package com.jianguozh.difs.support.service.component.file.core;

import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReflectUtil;
import com.jianguozh.difs.support.service.base.entity.Config;
import com.jianguozh.difs.support.service.base.service.IConfigService;
import com.jianguozh.difs.support.service.component.file.core.client.AbstractFileClient;
import com.jianguozh.difs.support.service.component.file.core.client.FileClientSetting;
import com.jianguozh.difs.support.service.constant.enums.ConfigTypeEnum;
import com.jianguozh.difs.support.service.constant.enums.FileStorageEnum;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * 文件客户端管理器
 *
 * @author hanrs
 * @email 4076130@qq.com
 * @since 2022/7/12 16:42
 */
@Component
@Slf4j
public class FileClientManager {

    @Resource
    private IConfigService configService;

    @Getter
    private AbstractFileClient fileClient;

    @PostConstruct
    public void initFileClient() {
        Config config = configService.getByType(ConfigTypeEnum.FILE_CLIENT_CONFIG);
        if (ObjectUtil.isNull(config)) {
            log.warn("文件存储器客户端配置不存在,无法完成文件客户端初始化.");
            return;
        }

        FileClientSetting fileClientSetting = (FileClientSetting) config.getSetting();
        fileClient = createFileClient(fileClientSetting);
        fileClient.init();
    }

    /**
     * 更新文件客户端
     *
     * @param fileClientSetting
     */
    public void updateFileClient(FileClientSetting fileClientSetting) {
        fileClient = createFileClient(fileClientSetting);
        fileClient.init();
    }

    /**
     * 客户端测试
     *
     * @param fileClientSetting
     * @return
     * @throws Exception
     */
    public String testFileClient(FileClientSetting fileClientSetting) throws Exception {
        AbstractFileClient testFileClient = createFileClient(fileClientSetting);
        testFileClient.init();
        byte[] content = ResourceUtil.readBytes("file/erweima.jpg");
        return testFileClient.upload(content, IdUtil.fastSimpleUUID() + ".jpg");
    }

    private <Setting extends FileClientSetting> AbstractFileClient<FileClientSetting> createFileClient(FileClientSetting fileClientSetting) {
        String fileStorage = fileClientSetting.getFileStorage();
        FileStorageEnum fileStorageEnum = FileStorageEnum.valueOf(fileStorage);
        return (AbstractFileClient<FileClientSetting>) ReflectUtil.newInstance(fileStorageEnum.getClientClass(), fileClientSetting);
    }

}
